package com.datang.pet.common.ossUtils;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.datang.pet.common.properties.OssAttr;

import java.sql.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-05-14 20:58
 * @notify 前端向阿里云上传文件时必须先取的Policy
 * @version 1.0
 */

public class WebSign {

    public static Map<String, String> getOssPolicy(Integer type)throws Exception {
        //三胞胎参数,不知道干啥的自己点进去看
        String endpoint = OssAttr.ENDPOINT;
        String accessId = OssAttr.ACCESSKEYID;
        String accessKey = OssAttr.ACCESSKEYSECRET;

        //往哪个文件夹存
        String bucket = OssUtil.getBucketName(type); //默认的bucketName 可以从阿里云的控制台自行创建 也可以使用api创建
        //有没有小文件夹存
        String dir = "";
        //bucket的地址
        String host = OssUtil.getBucketUrl(type);
        //阿里爸爸包装的类.呵呵
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        //装载返回值map
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        try {
            //policy 可用时间 30秒
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            //设置请求参数
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            //这特么其实就是在发http请求!!!怪我英文不好.呵呵呵呵
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            //拿到牛逼的policy
            byte[] binaryData = postPolicy.getBytes("utf-8");
            //阿里爸爸真装逼.自己加密.自己解密.
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            //ok其实这两个就是拿到的policy和sign
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            //这些都是我们自己提供的......
            respMap.put("accessid", accessId);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

        //JSONObject ja1 = JSONObject.fromObject(respMap);这一行耻辱代码留着....
        //读别人的代码不要看表面,要看本质.
 /*      <dependency>
           <groupId>net.sf.json-lib</groupId>
         <artifactId>json-lib</artifactId>
           <version>2.2.3</version>
           <classifier>jdk15</classifier>
       </dependency>*/
        } catch (Exception e) {
          throw new Exception("获取policy失败");
        }
        return respMap;
    }

}
